package com.sec.android.app.myfiles.util.animation;

import android.os.SystemClock;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class MoveAnimation extends Animation {

    private long mMoveDuration = 300L;
    private float mFromXDelta;
    private float mFromYDelta;
    private float mToXDelta;
    private float mToYDelta;

    public MoveAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta) {
        mFromXDelta = fromXDelta;
        mToXDelta = toXDelta;
        mFromYDelta = fromYDelta;
        mToYDelta = toYDelta;

        setDuration(mMoveDuration);
        setFillAfter(true);
        initialize(10, 10, 10, 10);
    }

    @Override
    public void setFillAfter(boolean fillAfter) {
        super.setFillAfter(fillAfter);
    }

    @Override
    public final void setDuration(long duration) {
        mMoveDuration = duration;
        super.setDuration(duration);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        float f1 = mFromXDelta;
        float f2 = mFromYDelta;

        t.clear();

        Transformation transformation = new Transformation();

        // Set Translate
        if (mFromXDelta != mToXDelta) {
            f1 = mFromXDelta + interpolatedTime * (mToXDelta - mFromXDelta);
        }

        if (mFromYDelta != mToYDelta) {
            f2 = mFromYDelta + interpolatedTime * (mToYDelta - mFromYDelta);
        }

        if (Float.compare(f1, f2) != 0) {
            transformation.getMatrix().setTranslate(f1, f2);
            t.compose(transformation);
            transformation.clear();
        }
    }

    private void swapMoveXY() {
        float tempFromX = mFromXDelta;
        float tempFromY = mFromYDelta;

        mFromXDelta = mToXDelta;
        mToXDelta = tempFromX;
        mFromYDelta = mToYDelta;
        mToYDelta = tempFromY;
    }

    public void reverseAnimation() {
        long curTime = SystemClock.uptimeMillis();
        long remainDurationTime = getDuration() - (curTime - getStartTime());

        swapMoveXY();

        if (!hasEnded()) {
            setStartTime(curTime - remainDurationTime);
        } else {
            setStartTime(-1L);
        }
    }

}
